package com.jijs.jmx.standard;

import java.lang.management.ManagementFactory;
import java.net.InetAddress;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

import javax.management.InstanceAlreadyExistsException;
import javax.management.MBeanRegistrationException;
import javax.management.MBeanServer;
import javax.management.MalformedObjectNameException;
import javax.management.NotCompliantMBeanException;
import javax.management.ObjectName;
import javax.management.remote.JMXConnectorServer;
import javax.management.remote.JMXConnectorServerFactory;
import javax.management.remote.JMXServiceURL;

import com.sun.jdmk.comm.HtmlAdaptorServer;

public class HelloAgent {

	/**
	 * 运行HelloAgent，然后打开网页： http://localhost:8082/,看效果!
	 * 
	 * @param args
	 * @throws MalformedObjectNameException
	 * @throws InstanceAlreadyExistsException
	 * @throws MBeanRegistrationException
	 * @throws NotCompliantMBeanException
	 */
	public static void main(String[] args) throws Exception {
		
		//如果启动时,加了以下参数,下面的五行代码就不需要了, JVM会自动帮我们执行Agent.premain方法
        StringBuilder param = new StringBuilder();
        param.append("com.sun.management.jmxremote.port=9999").append(",");
        param.append("com.sun.management.jmxremote.authenticate=false").append(",");
        param.append("com.sun.management.jmxremote.ssl=false").append(",");
//        sun.management.Agent.premain(param.toString());
        

		/**
		 * 说明：
		 * 
		 * • 先创建了一个 MBeanServer，用来做 MBean 的容器 • 将 Hello 这个类注入到 MBeanServer
		 * 中，注入需要创建一个 ObjectName 类
		 * 
		 * • 创建一个 AdaptorServer，这个类将决定 MBean 的管理界面，这里用最普 通的 Html 型界面。
		 * AdaptorServer 其实也是一个 MBean。
		 * 
		 * • jijs:name=HelloWorld 的名字是有一定规则的，格式为： “域 名:name=MBean 名称”，域名和 MBean
		 * 名称都可以任意取。
		 */
		// MBeanServer server = MBeanServerFactory.createMBeanServer();
		MBeanServer server = ManagementFactory.getPlatformMBeanServer();
		ObjectName helloName = new ObjectName("jijs:name=HelloWorld");
		server.registerMBean(new Hello(), helloName);

		ObjectName adapterName = new ObjectName(
				"HelloAgent:name=htmladapter,port=8082");
		HtmlAdaptorServer adapter = new HtmlAdaptorServer();
		server.registerMBean(adapter, adapterName);
		adapter.start();
		System.out.println("start.....");
		
		
		//Create an RMI connector and start it
		//这句话非常重要，不能缺少！注册一个端口，绑定url后，客户端就可以使用rmi通过url方式来连接JMXConnectorServer
		Registry registry = LocateRegistry.createRegistry(9999); 
		//或者 在cmd中执行 rmiregistry 8888 进行rmi注册端口
		
//		UnicastRemoteObject.unexportObject(registry, true);
        System.out.println("--");
        //java平台默认开启的jmx的rmi地址为service:jmx:rmi:///jndi/rmi://ip:port/jmxrmi
		JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://192.168.31.186:9999/jmxrmi");
		JMXConnectorServer cs = JMXConnectorServerFactory.newJMXConnectorServer(url, null, server);
		cs.start();
		System.out.println("rmi start.....");
	}
}
